var myFun = {
    getWMS: function (url, layerName) {
        var wms = new ol.layer.Image({
            source: new ol.source.ImageWMS({
                url: url,
                params: {LAYERS: layerName}
            }),
            zIndex: 6

        });
        return wms;
    },
    getTile: function (url, minZoom, maxZoom) {
        var tile = new ol.layer.Tile({
            source: new ol.source.XYZ({
                minZoom: minZoom,
                maxZoom: maxZoom,
                url: url
            }),
            zIndex: 0
        });
        return tile;
    },

    getElem: function (id) {
        return document.getElementById(id);
    },
    getLoc: function (js) {
        var loc = new Array;
        var count = js.length || 0;
        for (var x = 0; x < count; x++) {
            loc[x] = [parseFloat(js[x].lon), parseFloat(js[x].lat)];

        }
        return loc;
    },
    getLocName: function (js) {
        var locName = new Array;
        var count = js.length || 0;
        for (var x = 0; x < count; x++) {
            locName[x] = js[x].name;
        }
        var array = locName;
        return locName;
    },

    getData: function (js, m) {
        var data = new Array();
        var count = 0;
        if (js.length)
            count = js.length;
        for (var x = 0; x < count; x++) {
            switch (m) {

                case 0://'pm25'
                    data[x] = js[x].pm25;
                    break;
                case 1://'pm10':
                    data[x] = js[x].pm10;
                    break;
                case 2://'so2':
                    data[x] = js[x].so2;
                    break;
                case 3://'no2':
                    data[x] = js[x].no2;
                    break;
                case 4://'co':
                    data[x] = js[x].co;
                    break;
                case 5://'o3':
                    data[x] = js[x].o3;
                    break;
            }
        }
        return data;
    },
    getIco: function (parentPath, _count, scale) {
        var img = [];
        for (var i = 0; i < _count; i++) {
            img[i] = new ol.style.Icon({
                anchor: [0, 0],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                src: parentPath + '/' + i + ".png",
                scale: scale
            })
        }
        ;
        return img;
    },
    setLabel: function (ico, label, offx, offy) {
        var labelSt = new ol.style.Style({
            image: ico,
            text: new ol.style.Text({
                textAlign: 'middle',
                textBaseline: 'middle',
                font: 'normol 40px 微软雅黑',
                text: label.toString(),
                fill: new ol.style.Fill({color: "white"}),
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 2
                }),
                offsetX: offx,
                offsetY: offy
            })

        });
        return labelSt;
    },
    setLevel: function (lv) {
        var level = new Array();
        switch (lv) {
            case 1:
                return level = [50, 100, 150, 200, 300];//aqi
            case 2:
                return level = [35, 75, 115, 150, 250];//pm2.5
            case 3:
                return level = [50, 150, 250, 350, 420];//pm10
            case 4:
                return level = [50, 150, 475, 800, 1600];  //so2
            case 5:
                return level = [40, 80, 180, 280, 565];  //no2
            case 6:
                return level = [2, 4, 14, 24, 36];  //co
            case 7:
                return level = [100, 160, 215, 265, 800];    //o3

        }
    },
    setColor: function (value, type) {
        var level = myFun.setLevel(type);
        var color = [];
        color[0] = 'rgba(0,288,0,1)';
        color[1] = 'rgba(255,255,0,1)';
        color[2] = 'rgba(255,126,0,1)';
        color[3] = 'rgba(255,0,0,1)';
        color[4] = 'rgba(153,0,76,1)';
        color[5] = 'rgba(126,0,35,1)';
        fontcolor1 = 'white';
        fontcolor2 = 'black';

        if (value < level[0]) return [color[0], fontcolor2];
        else if (value < level[1]) return [color[1], fontcolor2];
        else if (value < level[2]) return [color[2], fontcolor2];
        else if (value < level[3]) return [color[3], fontcolor2];
        else if (value < level[4]) return [color[4], fontcolor1];
        else return [color[5], fontcolor1];
    },
    setClass: function (value) {
        var level = [50, 100, 150, 200, 300];
        var cls = ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染'];
        if (value <= level[0]) return cls[0];
        else if (value <= level[1]) return cls[1];
        else if (value <= level[2]) return cls[2];
        else if (value <= level[3]) return cls[3];
        else if (value <= level[4]) return cls[4];
        else return cls[5];
    },
//	setWeather:function(weather){
//		 (myFun.getElem("weatherContent")).innerHTML='<p>天气 ：'+weather[0]+'</p><p>温度 ：'+weather[1]+'</p><p>湿度 ：'+weather[2]+'%</p><p>风向 ：'+weather[3]+'</p><p>风速：' +weather[4]+'km/h</p><p>风级：'+weather[5]+'级</p>';
//	},
    setIndexSelect: function (bt) {
        for (var i = 1; i < 7; i++) {
            var _bt = myFun.getElem('indexButton' + i);
            _bt.style.backgroundColor = "";
            _bt.style.color = "gray";
        }
        bt.style.backgroundColor = "#eeeeee";
        bt.style.color = "#228B22";
    },
    labelSource: function (_json, _t) {
        var source = new ol.source.Vector();
        var ico = myFun.getIco('ico/class', 6, 1);
        var point = myFun.getLoc(_json);
        var label = myFun.getData(_json, _t - 1);
        var _locName = myFun.getLocName(_json);
        var count = point.length || 0;
        for (var i = 0; i < count; i++) {
            var pt = new ol.proj.fromLonLat(point[i]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(pt),
                name: [_json[i].name, _json[i].pm25, _json[i].pm10, _json[i].so2, _json[i].no2, _json[i].co, _json[i].o3]
            });

            var tem = label[i];
            var _lev = myFun.setLevel(_t);
            var _lev = myFun.setLevel(_t);
            if (tem < _lev[0])
                iconFeature.setStyle(myFun.setLabel(ico[0], label[i], 8, 12));
            else if (tem < _lev[1])
                iconFeature.setStyle(myFun.setLabel(ico[1], label[i], 3, 12));
            else if (tem < _lev[2])
                iconFeature.setStyle(myFun.setLabel(ico[2], label[i], 6, 12));
            else if (tem < _lev[3])
                iconFeature.setStyle(myFun.setLabel(ico[3], label[i], 6, 12));
            else if (tem < _lev[4])
                iconFeature.setStyle(myFun.setLabel(ico[4], label[i], 6, 12));
            else
                iconFeature.setStyle(myFun.setLabel(ico[5], label[i], 6, 12));

            var nameFeature = new ol.Feature({
                geometry: new ol.geom.Point(pt),
                name: [_json[i].name, _json[i].pm25, _json[i].pm10, _json[i].so2, _json[i].no2, _json[i].co, _json[i].o3]     //保证点击名字也能等同于点中图标
            });
            nameFeature.setStyle(myFun.setLabel(null, _locName[i], 35, 5));
            source.addFeature(iconFeature);
            source.addFeature(nameFeature);
        }
        return source;
    },
    eventPopu: function () {
        selectpt.on('select', function (e) {
            if (e.selected.length > 0) {
                //set Value
                var popuBts;
                for (var i = 1; i < 7; i++) {
                    popuBts = myFun.getElem('popu-' + i);
                    popuBts.innerHTML = e.selected["0"].S.name[i];
                }

                myFun.getElem('popu-8').innerHTML = myFun.setClass(parseFloat(e.selected["0"].S.name[1]));
                var popuCity = myFun.getElem('popu-city');
                popuCity.innerHTML = e.selected["0"].S.name[0];
                //set color
                var colorBts;
                for (var u = 1; u < 7; u++) {
                    colorBts = myFun.getElem('_color' + u);
                    var _blockColor = myFun.setColor(parseFloat(e.selected["0"].S.name[u]), u);
                    colorBts.style.backgroundColor = _blockColor[0];
                    colorBts.style.color = _blockColor[1];
                }
                var colorBts8 = myFun.getElem('_color' + 8);
                var color8 = myFun.setColor(parseFloat(e.selected["0"].S.name[1]), 1);
                colorBts8.style.backgroundColor = color8[0];
                colorBts8.style.color = color8[1];

                //set Weather
//					var weather=['晴',25,55,'西风',12,5];
//					myFun.setWeather(weather);
                //set Show
                myFun.getElem('popu').style.display = "block";
                overlay.setPosition(e.mapBrowserEvent.coordinate);
            }
            else {
                myFun.getElem('popu').style.display = "none";
                overlay.setPosition(undefined);
            }
        });
    }
}
/////////////////////////////////////////////////////////////
//全局变量
var indexLayer = 0,
    indexLayerShi = 0,
    vectorLayer,
    vectorLayerShi,
    indexArea = 0,
    layerArea,
    show = false;

var overlay = createOverlay('popu', '_close');  //新建Overlay
var map = createMap();//新建Map
var selectpt = createSelect(); //新建select
layerSwitch();  //图层切换功能
areaAnl(map);


$(document).ready(function () {
    $.get('/hbtserver/station/query?shi=shi', function (result, st) {
        var js01 = $.parseJSON(result);
        $.get('/hbtserver/station/query?shi=gk', function (result2, st2) {
            var js02 = $.parseJSON(result2);
            init(js01, js02);
            eventIndex(js01, js02);
            showGK_SK(js01, js02);

            $('#sateButton1').click(function () {
                $('#sateButton1').css({backgroundColor: 'green'});
                $('#sateButton2').css({backgroundColor: 'gray'});
                init(js01, js02);
                eventIndex(js01, js02);
                showGK_SK(js01, js02);
            });
        });

        $.get('/hbtserver/station/query?shi=sk', function (result3, st3) {
            var js03 = $.parseJSON(result3);
            $('#sateButton2').click(function () {
                $('#sateButton2').css({backgroundColor: 'green'});
                $('#sateButton1').css({backgroundColor: 'gray'});
                init(js01, js03);
                eventIndex(js01, js03);
                showGK_SK(js01, js03);
            });
        });

    });


});

//--------------function-----------------
function getImgUrl(num) {
    switch (num) {
        case 1:
            return '/hbtmap/childHTML/003/data/aqi.png';
        case 2:
            return '/hbtmap/childHTML/003/data/pm25.png';
        case 3:
            return '/hbtmap/childHTML/003/data/pm10.png';
        case 4:
            return '/hbtmap/childHTML/003/data/so2.png';
        case 5:
            return '/hbtmap/childHTML/003/data/no2.png';
        case 6:
            return '/hbtmap/childHTML/003/data/co.png';
        case 7:
            return '/hbtmap/childHTML/003/data/o3.png';
    }
}

function areaAnl(map, num) {
    var path = getImgUrl(num) || getImgUrl(1);
    if (show) {
        map.removeLayer(layerArea);
        show = false;
    }
    var pt = [110.354301450338, 31.3756321479311, 116.654301450338, 36.3756321479311],
        ptxy1 = new ol.proj.fromLonLat([pt[0], pt[1]]),
        ptxy2 = new ol.proj.fromLonLat([pt[2], pt[3]]),
        extent = [ptxy1[0], ptxy1[1], ptxy2[0], ptxy2[1]];

    var projection = new ol.proj.Projection({
        code: 'xkcd-image',
        units: 'pixels',
        extent: extent
    });
    layerArea = new ol.layer.Image({
        zIndex: 5,
        source: new ol.source.ImageStatic({
            url: path,
            projection: projection,
            imageExtent: extent
        })
    });
    map.addLayer(layerArea);
    show = true;
}

function init(js_shi, js) {
    var bt = myFun.getElem('indexButton1');
    myFun.setIndexSelect(bt);
    //初始加载
    if (indexLayerShi)
        map.removeLayer(vectorLayerShi);
    vectorLayerShi = new ol.layer.Vector({
        source: myFun.labelSource(js_shi, 1),
        zIndex: 7,
        maxResolution: 4891
    });
    map.addLayer(vectorLayerShi);
    indexLayerShi = 1;
    showGK_SK(js_shi, js);//Zoom功能  预加载gk
}

function eventIndex(js_shi, js) {
    var indexBts = new Array();
    for (var id = 1; id < 7; id++) {
        indexBts[id - 1] = myFun.getElem('indexButton' + id);
        addIndexEvent(js, js_shi, indexBts[id - 1], id);
    }

    function addIndexEvent(js, js_shi, bt, tt) {
        bt.onclick = function () {
            //ui
            myFun.setIndexSelect(bt);
            //data
            if (indexLayer) {
                map.removeLayer(vectorLayer);
                indexLayer = 0;
            }
            if (indexLayerShi) {
                map.removeLayer(vectorLayerShi);
                indexLayerShi = 0;
            }

            vectorLayer = new ol.layer.Vector({
                source: myFun.labelSource(js, tt),
                zIndex: 7,
                visible: true,
                maxResolution: 452
            });
            vectorLayerShi = new ol.layer.Vector({
                source: myFun.labelSource(js_shi, tt),
                zIndex: 7,
                visible: true,
                maxResolution: 4891
            });

            map.addLayer(vectorLayer);
            indexLayer = 1;

            map.addLayer(vectorLayerShi);
            indexLayerShi = 1;
            areaAnl(map, tt);
        }
    }
}

function showGK_SK(js_shi, js) {
    if (indexLayer) {
        map.removeLayer(vectorLayer);
        indexLayer = 0;
    }
    vectorLayer = new ol.layer.Vector({
        source: myFun.labelSource(js, 1),
        zIndex: 7,
        maxResolution: 452
    });

    map.addLayer(vectorLayer);
    indexLayer = 1;
    myFun.eventPopu();
    eventIndex(js_shi, js);
}

function createOverlay(id1, id2) {
    var popu = myFun.getElem(id1);
    var popuCloser = myFun.getElem(id2);

    var overlay = new ol.Overlay({
        element: popu,
        autoPan: true,
        autoPanAnimation: {
            duration: 250
        }
    });
    popuCloser.onclick = function () {
        overlay.setPosition(undefined);
        popuCloser.blur();
        return false;
    };
    return overlay;
}

function createMap() {
    var ct = new ol.proj.fromLonLat([113.650047, 34.757034]);
    console.log(ct);
    //[12334721.93, 4010915.35]
    var map = new ol.Map({
        controls: ol.control.defaults({attributionOptions: ({collapsible: false})}),
        layers: [],
        target: 'map',
        view: new ol.View({center: ct, zoom: 7}),
        overlays: [overlay]
    });
    return map;
}

function createSelect() {
    var selectpt = new ol.interaction.Select({
        condition: ol.events.condition.pointerMove// ol.events.condition.click   //点击弹出 或者移动弹出
    });
    map.addInteraction(selectpt);
    return selectpt;
}


function layerSwitch() {
    var flag = 0;
    var wms, road, sate, terrain, henanBJ;
    //从服务端加载图层
    wms = myFun.getTile('/data/google/overlay/{z}/{x}/{y}.png', 1, 14);
    road = myFun.getTile('/data/google/roadmap/{z}/{x}/{y}.png', 0, 14),
        sate = myFun.getTile('/data/google/satellite/{z}/{x}/{y}.jpg', 0, 14),
        terrain = myFun.getTile('/data/google/terrain/{z}/{x}/{y}.jpg', 0, 14),
        henanBJ = myFun.getWMS('/geoserver/wms', 'hbt:huanbaoting');
    //初始状态
    preDo(flag);
    map.addLayer(sate);
    map.addLayer(henanBJ);
    map.addLayer(wms);
    flag = 1;
    //event
    layerUI(flag);

    //function
    function preDo(flag) {
        if (flag === 1) map.removeLayer(sate);
        if (flag === 2) map.removeLayer(road);
        if (flag === 3) map.removeLayer(terrain);
        flag = 0;
    }

    function layerUI(flag) {
        $('.bt7_btn').click(function (et) {
            preDo(flag);
            $('#layerButton1,#layerButton2,#layerButton3').css({backgroundColor: 'gray'});
            switch (et.target.id) {
                case 'layerButton1': {
                    $('#layerButton1').css({backgroundColor: 'green'});
                    map.addLayer(sate);
                    flag = 1;
                    break;
                }
                case 'layerButton2': {
                    $('#layerButton2').css({backgroundColor: 'green'});
                    map.addLayer(road);
                    flag = 2;
                    break;
                }
                case 'layerButton3': {
                    $('#layerButton3').css({backgroundColor: 'green'});
                    map.addLayer(terrain);
                    flag = 3;
                    break;
                }
            }

        });
    }
}

		
	